<?php
namespace Handlers;

class YopurmaqInformationHandler extends Handler
{
    protected $index_base = 'v3_yopurmaq_information_';

    public $fields = [
        'id' => 'int',
        'uuid' => 'string',
        'category_id' => 'int',
        'district_id' => 'int',
        'title' => 'string',
        'thumb' => 'string', 
        'video' => 'boolean', 
        'individual_member_id' => 'int',
        'updated_at' => 'datetime', 
        'content' => 'json', 
    ];

    public function insertOrUpdate(array $data, $tableId = 0, $insertRawData = false) {

        // echo 'RAW DATA:' . PHP_EOL;
        // print_r($data);

        $id = (int)$data['id'];
        $cid = $data['category_id'];
        $tid = $tableId ? $tableId : $this->getParentIdByCateId($cid);
        
        $info = $insertRawData ? $data : $this->fetchInfoFromMysql($id, $tid);

        $params = [
            'index' => $this->index_base . $tid,
            'id' => $id,
            'type' => '_doc',
            'body' => $info
        ];

        $this->log('info', 'input:', $params);
        
        try {
            $res = $this->getEs()->index($params);
        } catch (\Exception $t) {
            $this->log('error', 'insert or update exception: ' . $t->getMessage());
            $this->log('error', 'ERROR DETAIL: ' . var_export($data, true) );
            return ;
        }
        
        $this->log('info', 'result: ' . $res['result']);
    }

    public function delete(array $data, $tableId = 0) {
        
        $id = (int)$data['id'];
        $cid = $data['category_id'];
        $tid = $tableId ? $tableId : $this->getParentIdByCateId($cid);

        $params = [
            'index' => $this->index_base . $tid,
            'type' => '_doc',
            'id' => $id
        ];

        $this->log('info', 'input:' . json_encode($params));
        
        try {
            $res = $this->getEs()->delete($params);
        } catch (\Exception $t) {
            $this->log('error', 'delete exception: ' . $t->getMessage());
            $this->log('error', 'ERROR DETAIL: ' . var_export($data, true) );
            return ;
        }
        $this->log('info', 'result: ' . $res['result']);
    }

    public function formatData($columns) {
        $fieldNames = array_keys($this->fields);
        
        $arr = [];

        foreach ($columns as $column) {
            $name = $column->getName();
            $value = $column->getValue();

            if (! in_array($name, $fieldNames)) {
                continue;
            }

            $value = $this->changeFieldValueType($name, $value);

            $arr[$name] = $value;
        }

        // 校正数据
        if (isset($arr['content'])) {
            $arr['content'] = $this->contentCorrection($arr['content']);
        }

        return (array)$arr;
    }

    function fetchInfoFromMysql($id, $tid) {
        $individual_member_id_field = $this->getIndividualMemberIdField($tid);

$sql = <<<EOD
SELECT
i.id AS id, 
i.uuid AS uuid, 
category_id, 
district_id, 
title, 
thumb, 
video, 
updated_at,
{$individual_member_id_field}
ic.content AS content
from information_? as i, information_content as ic
where i.id = ? and i.uuid = ic.uuid
EOD;
        $row = $this->connect->fetch($sql, $tid, $id);
     
        return $this->formatMysqlData((array)$row);
    }

    public function formatMysqlData(array $row) { 

        $fieldNames = array_keys($this->fields);
        
        $arr = [];

        foreach ($row as $name => $value) {

            if (! in_array($name, $fieldNames)) {
                continue;
            }

            $value = $this->changeFieldValueType($name, $value);

            $arr[$name] = $value;
        }

        // 校正数据
        if (isset($arr['content'])) {
            $arr['content'] = $this->contentCorrection($arr['content']);
        }

        return (array)$arr;
    }

    function contentCorrection(array $data, $remove_sensitive = true) {
        if ($remove_sensitive) {
            unset($data['content']->_mobile);
            unset($data['content']->_qrcode);
        }

        if (isset($data['bahasi'])) {
            $data['bahasi'] = (int)$data['bahasi'];
        }

        if (isset($data['kulimi'])) {
            $data['kulimi'] = (int)$data['kulimi'];
        }

        return $data;
    }

    function getParentIdByCateId($cid) {
        $row = (array)$this->connect->fetch('SELECT id, parent_id FROM categorys WHERE id = ?', $cid);
      
        return empty($row['parent_id']) ? $cid : $row['parent_id'];
    }

    function getIndividualMemberIdField($tid) {
        $table = 'information_' . $tid;

        // 判断individual_member_id属性是否存在
        $r = $this->connect->fetchField("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '{$table}' AND COLUMN_NAME = 'individual_member_id'");
        return $r ? "{$r}," : '';
    }

}
